package com.bulunsh.wensen.interceptor;

import com.bulunsh.wensen.model.UserDto;
import com.sun.corba.se.spi.ior.WriteContents;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检验身份
        Object o = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if (o == null) {
            writeContents(response,"please login");
        }
        UserDto userDto = (UserDto)o;
        String uri = request.getRequestURI();
        if (uri.contains("/r/r1") && userDto.getAuthorities().contains("r1")){
            return true;
        }
        if (uri.contains("/r/r2") && userDto.getAuthorities().contains("r2")){
            return true;
        }
        writeContents(response,"no permisson");
        return false;
    }

    //响应信息给前端
    private void writeContents(HttpServletResponse response, String message) throws IOException {

        PrintWriter printWriter = response.getWriter();
        printWriter.write(message);
        printWriter.close();

    }
}
